package com.oddfar.campus.business.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oddfar.campus.business.domain.entity.SensitiveEntity;
import com.oddfar.campus.business.enums.CampusBizCodeEnum;
import com.oddfar.campus.business.mapper.SensitiveMapper;
import com.oddfar.campus.business.service.SensitiveService;
import com.oddfar.campus.common.core.LambdaQueryWrapperX;
import com.oddfar.campus.common.domain.PageResult;
import com.oddfar.campus.common.exception.ServiceException;
import com.oddfar.campus.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SensitiveServiceImpl extends ServiceImpl<SensitiveMapper, SensitiveEntity>
        implements SensitiveService {

    @Autowired
    private SensitiveMapper sensitiveMapper;

    @Override
    public PageResult<SensitiveEntity> page(SensitiveEntity sensitive) {
        return sensitiveMapper.selectPage(sensitive);
    }

    @Override
    public int insertSensitive(SensitiveEntity sensitive) {
        checkAddOrUpdate(sensitive);
        return sensitiveMapper.insert(sensitive);
    }

    @Override
    public int updateSensitive(SensitiveEntity sensitive) {
        checkAddOrUpdate(sensitive);
        return sensitiveMapper.updateById(sensitive);
    }

    // @Override
    // public List<ContentSensitiveEntity> getSensitiveListByContentIds(List<Long> contentIds) {
    //     List<ContentSensitiveEntity> sensitiveEntities = sensitiveMapper.selectSensitiveListByContentIds(contentIds);
    //     return sensitiveEntities;
    // }

    @Override
    public boolean checkNameUnique(SensitiveEntity sensitive) {
        Long sensitiveId = StringUtils.isNull(sensitive.getSensitiveId()) ? -1L : sensitive.getSensitiveId();
        SensitiveEntity info = sensitiveMapper.selectOne(new LambdaQueryWrapperX<SensitiveEntity>()
                .eq(SensitiveEntity::getSensitiveName, sensitive.getSensitiveName()));
        if (StringUtils.isNotNull(info) && info.getSensitiveId().longValue() != sensitiveId.longValue()) {
            return false;
        }
        return true;
    }

    /**
     * 是否可以添加标签
     *
     * @param sensitiveEntity
     * @return true可以添加
     */
    private boolean checkAddOrUpdate(SensitiveEntity sensitiveEntity) {
        if (!checkNameUnique(sensitiveEntity)) {
            throw new ServiceException(CampusBizCodeEnum.SENSITIVE_NAME_REPEAT.getMsg(),
                    CampusBizCodeEnum.SENSITIVE_NAME_REPEAT.getCode());
        }

        return true;
    }

}
